<?php
namespace Api\Controller;
use Home\Model\MemberModel;
use Common\Controller\ApiController;

class RegisterController extends ApiController {
    
    function _initialize() {
        parent::_initialize();
        //验证 APP KEY
        $timestamp = I('request.timestamp');
        $token = I('request.token');
        parent::checkAppToken($token,$timestamp);
    }
    
    //登陆提交
    function login_submit() {
        $data['code'] = '200';
        $data['msg'] = '';
        $MemberObj = new MemberModel();
        $username = trim(I('post.username',''));
        $password = trim(I('post.password',''));
        if (trim($username) == '' || trim($password) == '') {
            $data['code'] = '500';
            $data['msg'] = '用户名或密码不能为空';
        } else {
            $arr = $MemberObj->field('member_id,status,username,email,phone')->where(Array('username|email|phone' => $username, 'password' => $password))->find();
            if (is_array($arr)) {
                if ($arr['status'] != 1) {
                    $data['code'] = '500';
                    $data['msg'] = '用户已被禁用';
                } else {
                    $key_login_code = $arr['member_id'] . randomname(30);
                    $arr['code_keep_login'] = $key_login_code;
                    $MemberObj->save($arr);

                    //登录信息
                    $LoginObj = new \Home\Model\MemberLoginModel();
                    $LoginObj->add_login_record($arr['member_id']);
                    //登陆赠送积分
                    $MemberPointObj = new \Fwadmin\Model\MemberPointModel();
                    $config = S('config');
                    $MemberPointObj->add_by_login($arr['member_id'], $config['point_login_day']);
                    $data['data'] = array('code_keep_login'=>$arr['code_keep_login'],'member_id'=>$arr['member_id'],'username'=>$arr['username'],'email'=>$arr['email'],'phone'=>$arr['phone']);
                }
            } else {
                $data['code'] = '500';
                $data['msg'] = '用户名或密码不能为空';
            }
        }
        $this->response($data,C('API_TYPE'));
    }
    
    //注册发送手机验证码
    public function send_phone_code($phone) {
        $MemberObj = new MemberModel();
        if (!is_phone($phone)) {
            $result['code'] = '500';
            $result['msg'] = '手机号码格式不对';
        } elseif ($MemberObj->exist_phone($phone,0) > 0 && $phone != "13927430895") {
            $result['code'] = '500';
            $result['msg'] = '手机号码已注册，你可以直接登陆';
        } else {
            $phone_code = rand(100000, 999999);
            $content = "您的验证码为".$phone_code."，在20分钟内有效。";
            if(sendSMS($phone, $content) == 'success') {
                $result['code'] = '200';
                $result['data'] = "".$phone_code."";
                $result['msg'] = '发送成功';
            } else {
                $result['code'] = '500';
                $result['msg'] = '发送失败！';
            }
        }
        $this->response($result,C('API_TYPE'));
    }
    
    //注册提交
    function register_submit() {
        $result['code'] = '200';
        $MemberObj = new MemberModel();
        $verify = new \Think\Verify();
        $email = trim(I('post.email',''));
        $phone = trim(I('post.phone',''));
        $password = trim(I('post.password',''));
        $phone_validate_code = trim(I('post.phone_validate_code',''));
        $result['title']='success';
        $phone_code = session('phone_code');
        $phone_no = session('phone_no');
        if (empty($email) && empty($phone)) {
            $result['code']='500';
            $result['msg']='请输入邮箱或手机！';
        } elseif (!empty($email) &&  !is_email($email)) {
            $result['code']='500';
            $result['msg']='邮箱格式错误！';
        } elseif (!empty($phone) &&  !is_phone($phone)) {
            $result['code']='500';        
            $result['msg']='手机格式有误！';
        } elseif (!empty($email) && $MemberObj->exist_email($email, 0)>0){
            $result['code']='500';
            $result['msg']='此邮箱已被使用！';
        } elseif(!empty($phone) && $MemberObj->exist_phone($phone, 0)>0) {
            $result['code']='500';
            $result['msg']='此手机已被使用！';
        } elseif ($password == '') {
            $result['code']='500';
            $result['msg']='请填写密码！';
//        } elseif ($phone_validate_code == '') {
//            $result['code']='500';
//            $result['msg']='请输入手机验证码！';
        } else {
            $member_id = $MemberObj->register($email, $phone,'', $password);
            if($member_id > 0) {
                $result['code']='200';
            } else {
                $result['code']='500';
                $result['msg']='系统繁忙，注册失败！';
            }
        }
        $this->response($result,C('API_TYPE'));
    }
    
    //退出登陆
    public function logout_ajax()
    {
        $MemberObj = new \Home\Model\MemberModel();
        $MemberObj->logout();
        echo '1';
    }
    
    //验证用户名是否重名
    public function exist_nickname($e) {
        $MemberObj = new MemberModel();
        echo $MemberObj->exist_nickname($e, 0);
    }
    
    //验证邮箱是否重名
    public function exist_email($e) {
        $MemberObj = new MemberModel();
        echo $MemberObj->exist_email($e, 0);
    }
    
    //验证手机是否重名
    public function exist_phone($e) {
        $MemberObj = new MemberModel();
        echo $MemberObj->exist_phone($e, 0);
    }
    
    //验证验证码是否正确
    public function check_valid_code($e) {
        $verify = new \Think\Verify();
        if($verify->check($e)) {
            echo '1';
        } else {
            echo '0';
        }
    }
    
    //显示验证码
    public function verify() {
        layout(false);
        $Verify = new \Think\Verify();
        $Verify->fontSize = 24;
        $Verify->useImgBg = false;
        $Verify->length = 4;
        $Verify->useNoise = false;
        $Verify->useCurve = false;
        $Verify->codeSet = '0123456789';
        $Verify->entry();
    }
    

    
    //找回密码发送手机验证码 
    public function get_phone_code2($phone) {
        $MemberObj = new MemberModel();
        if (!is_phone($phone)) {
            $result['code'] = '400';
            $result['message'] = '手机号码格式不对';
        } else {
            $phone_code = rand(100000, 999999);
            session('phone_code',$phone_code);
            session('phone_no',$phone);
            $content = "您的验证码为".$phone_code."，在20分钟内有效。";
            if(sendSMS($phone, $content) == 'success') {
                $result['code'] = '200';
                $result['message'] = '手机验证短信发送成功';
            } else {
                $result['code'] = '400';
                $result['message'] = '手机验证短信发送失败！';
            }
        }
        return $this->ajaxReturn($result);
    }
    
    //找回密码
    public function forget() {
        $this->display();
    }
    
    //找回密码发送邮件
    public function forget_email() {
        $email = trim(I('post.email',''));
        $validate_code = trim(I('post.validate_code',''));
        $MemberObj = new \Home\Model\MemberModel();
        if(empty($email)) {
            echo '请输入邮箱地址！';
            exit();
        }
        $verify = new \Think\Verify();
        if ($validate_code == '' || !$verify->check($validate_code)) {
            echo '请输入验证码或者验证码不对！';
            exit();
        }
        if($MemberObj->exist_email($email,0) <= 0) {
            echo '用户不存在！';
            exit();
        }
        $config = S('config');
        $member_id = $MemberObj->getFieldByEmail($email,'member_id');
        $member_name = $MemberObj->show_member_name($member_id);
        $status = $MemberObj->getFieldByMemberId($member_id,'status');
        if($status !== '1') {
            echo '用户已被禁用或删除！';
            exit();
        }
        $code_find_password = randomname(18).$member_id;
        $MemberInfoObj = new \Home\Model\MemberInfoModel();
        $MemberInfoObj->where('member_id='.$member_id)->setField('code_find_password',$code_find_password);
        $host = get_host();
        $url = $host.U('Register/forget_reset',array('code'=>$code_find_password));
        $url2 = '<a href="'.$url.'" target="_blank">'.$url.'</a>';
        $title = $config['forget_email_title'];
        $content = htmlspecialchars_decode($config['forget_email_detail']);
        $content = str_replace("{nickname}", $member_name, $content);
        $content = str_replace("{url}",$url2,$content);
        $content = '<html><body>'.$content.'</body></html>';
        $flag = sendMail($email, $title, $content);
        if($flag > 0) {
            echo '找回密码邮件发送成功，请到你的邮箱'.$email.'查看';
            exit();
        } else {
            echo '系统邮件发送失败，请联系网站客服！';
            exit();   
        }  
    }
    
    //手机找回密码
    public function forget_phone_ajax() {
        $phone_validate_code = trim(I('post.phone_validate_code',''));
        $phone = trim(I('post.phone',''));
        $phone_code = session('phone_code');
        $phone_no =  session('phone_no');
        if($phone_no == $phone && $phone_code == $phone_validate_code) {    
            $new_password = trim(I('post.password_new',''));
            $new_password = strongmd5($new_password);
            $MemberObj = new \Home\Model\MemberModel();
            $flag = $MemberObj->where(array('phone'=> $phone))->setField('password', $new_password);
            if($flag !== false) {
                session('phone_code',nul);
                session('phone_no',nul);
                echo 'success';
            } else {
                echo '修改失败！';
            }
        } else {
            echo '手机验证码错误！';
        }
    }
    
    //邮箱重置密码界面
    public function forget_reset() {
        $c = I('get.code','');
        if(empty($c)) {
            redirect(U('login'));
        } else {
            $MemberInfoObj = new \Home\Model\MemberInfoModel();
            $MemberObj = new \Home\Model\MemberModel();
            $member_id = $MemberInfoObj->where(array('code_find_password'=>$c))->getField('member_id');
            if(empty($member_id)) {
                $this->error('校验码己失效',U('forget'));
            }
            $this->member_name = $MemberObj->show_member_name($member_id);
            $this->code = $c;
            $this->display();
        }
    }
    
    //邮箱重置密码提交 AJAX
    public function forget_reset_ajax() {
        $c = trim(I('post.code',''));
        if(empty($c)) {
            echo '非法操作';
            exit();
        }
        $MemberInfoObj = new \Home\Model\MemberInfoModel();
        $MemberObj = new \Home\Model\MemberModel();
        $member_id = $MemberInfoObj->where(array('code_find_password'=>$c))->getField('member_id');
        if($member_id <= 0) {
            echo '非法操作';
            exit();
        }
        $new_password = trim(I('post.password',''));
        $new_password = strongmd5($new_password);
        $old_password = $MemberObj->where(array('member_id'=> $member_id))->getField('password');
        if($new_password == $old_password) {
            echo '新密码与原密码一致';
            exit();
        }
        $flag = $MemberObj->where(array('member_id'=> $member_id))->setField('password', $new_password);
        if($flag > 0) {
            $MemberInfoObj->where(array('member_id'=> $member_id))->setField('code_find_password', '');
            echo 'success';
        } else {
            echo '修改失败！';
        }
    }
}